package com.oa.core.utils;

import com.alibaba.fastjson.JSONObject;
import com.oa.core.config.WechatConfig;
import com.simm.common.utils.HttpUtil;
import org.springframework.util.StringUtils;

public class CompanyWechatUtil {

    /**
     *
     * @Description 生成用于获取access_token的Code的Url
     *
     * @author YingJH
     * @Date 2018年1月24日
     * @param redirectUrl
     * @return
     */
    public static String buildRequestCodeUrl(String redirectUrl) {
        return String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect",
                        WechatConfig.publicNumberAppid, redirectUrl, "snsapi_base", "1");
    }



    /**
     *@Title getUserId
     *@Description TODO
     *@author Yingjianghua
     *@date 14:30 2018/8/13
     *@param [code, token]
     *@return java.lang.String
     */
    public static String getUserId(String code, String token) {
        String url = String.format("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=%s&code=%s",
                token, code);
        String result = HttpUtil.HttpConnect(url);
        JSONObject object = JSONObject.parseObject(result);
        return (String) object.get("UserId");
    }

    /**
     * 获取token
     *
     * @return
     */
    public static String getToken() {
        String url = bulidURL();
        String weChatToken = HttpUtil.HttpConnect(url);
        if (StringUtils.hasLength(weChatToken)) {
            com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(weChatToken);
            weChatToken = object.get("access_token").toString();
            return weChatToken;
        }
        return null;
    }

    public static String bulidURL(){
        StringBuilder sb = new StringBuilder("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=");
        sb.append(WechatConfig.publicNumberAppid);
        sb.append("&corpsecret=");
        sb.append(WechatConfig.publicNumberSecret);
        String sbStr = sb.toString();
        return sbStr;
    }
}
